package com.kevin.controller.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kevin.common.api.R;
import com.kevin.common.exception.BusinessException;
import com.kevin.service.entity.SysOrg;
import com.kevin.service.entity.SysUser;
import com.kevin.service.service.SysOrgService;
import com.kevin.service.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 机构管理
 *
 * @author 阿沐 babamu@126.com
 */
@RestController
@RequestMapping("sys/org")
@Api(tags = "机构管理")
@AllArgsConstructor
public class SysOrgController {
    private final SysOrgService orgService;
    private final SysUserService userService;

    @GetMapping("list")
    @ApiOperation(value = "列表")
    @SaCheckPermission(value = "sys:org:list")
    public R<List<SysOrg>> list() {
        return R.ok(orgService.list());
    }

    @GetMapping("{id}")
    @ApiOperation(value = "信息")
    @SaCheckPermission(value = "sys:org:info")
    public R<SysOrg> get(@PathVariable("id") Long id) {
        SysOrg entity = orgService.getById(id);

        // 获取上级机构名称
        if (0L != (entity.getPid())) {
            SysOrg parentEntity = orgService.getById(entity.getPid());
            entity.setParentName(parentEntity.getName());
        }
        return R.ok(entity);
    }

    @PostMapping
    @ApiOperation(value = "保存")
    @SaCheckPermission(value = "sys:org:save")
    public R<String> save(@RequestBody @Valid SysOrg vo) {
        orgService.save(vo);
        return R.ok();
    }

    @PutMapping
    @ApiOperation(value = "修改")
    @SaCheckPermission(value = "sys:org:update")
    public R<String> update(@RequestBody @Valid SysOrg entity) {

        // 上级机构不能为自身
        if (entity.getId().equals(entity.getPid())) {
            throw new BusinessException("上级机构不能为自身");
        }

        // 上级机构不能为下级
        List<Long> subOrgList = orgService.getSubOrgIdList(entity.getId());
        if (subOrgList.contains(entity.getPid())) {
            throw new BusinessException("上级机构不能为下级");
        }

        orgService.updateById(entity);
        return R.ok();
    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "删除")
    @SaCheckPermission(value = "sys:org:delete")
    public R<String> delete(@PathVariable("id") Long id) {
        // 判断是否有子机构
        Assert.isTrue(orgService.count(Wrappers.lambdaQuery(SysOrg.builder().pid(id).build())) <= 0, "请先删除子机构");
        // 判断机构下面是否有用户
        Assert.isTrue(userService.count(Wrappers.lambdaQuery(SysUser.builder().orgId(id).build())) <= 0, "机构下面有用户，不能删除");
        orgService.removeById(id);
        return R.ok();
    }

}
